<!-- 指标配置-配置机构 -->
<template>
  <view class="s-list">
    <Header :title="title" bgColor="#fff" :leftIconSize="20"/>
    <!-- 搜索 -->
    <view class='search-content'>
      <view class="left">
        <uv-search :clearabled="true" bgColor="#fff" v-model="queryForm.name" :placeholder="placeholder" :showAction='false' @change="searchFun()" @clear="clearFun()"/>
      </view>
      <view class="screen-icon" @click="showPicker">
        <image v-if="iconFlag === true" src="@/static/image/index/icon2.png" mode="widthFix"/>
        <image v-else src="@/static/image/index/icon1.png"  mode="widthFix"/>
      </view>
    </view>
    <!-- 主内容 -->
    <view class='s-list-main'>
      <view class='s-box pad25'>
        <view class='s-check-box' style="height: 45px;">
          <uv-checkbox-group v-model="allBoxValue" iconPlacement="left" placement="column" v-if="checkType!==1">
            <uv-checkbox :checked="allCheck" name="apple" label="全选" @change="allChecked"/>
          </uv-checkbox-group>
          <checkbox-group @change="allChecked" v-if="checkType===1">
            <label class="cu-checked-group">
              <checkbox hidden color="#FFFFFF" value="2" />
              <view class="cu-checkbox check-not-full">
                <view class="uni-checkbox-input"></view>
              </view>
              <text class="text">全选</text>
            </label>
          </checkbox-group>
          <view class="right">
            已选择:{{ checkboxValue.length > groupList.length ? groupList.length : checkboxValue.length }}/{{ groupList.length }}
          </view>
        </view>
        <view class="s-check-group">
          <uv-checkbox-group v-model="checkboxValue" iconPlacement="left" placement="column" @change="changeCheckbox">
            <uv-checkbox :checked="item.checked" :name="item.id" :label="item.name" v-for="(item,index) in groupList" :key="index"/>
          </uv-checkbox-group>
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class='s-btn-common'>
      <uv-button type="primary" text="确认" :disabled="loading" @click="confirmFun()"/>
    </view>
    <!-- 筛选的下拉 -->
    <uv-action-sheet ref="searchPicker" title="筛选" :closeOnClickOverlay="false" :closeOnClickAction="false" @close="close">
      <slot>
        <view class="search-picker-main">
          <view class='search-picker-top'>
            <!-- 办学性质 -->
            <view v-if="entryType !== '5'" class="institution-box">
              <view class="title">办学性质</view>
              <view class="main">
                <!-- 循环 -->
                <view v-for="(item,index) in schoolNatureList" :key="index"
                      :class="{active:item.value === schoolNature}" @click="schoolNatureFun(item)">
                  {{ item.name }}
                </view>
              </view>
            </view>
            <!-- 办学类型 -->
            <view v-if="entryType !== '5'" class="institution-box">
              <view class="title">办学类型</view>
              <view class="main">
                <!-- 循环 -->
                <view v-for="(item,index) in schoolTypeList" :key="index"
                      :class="{active:item.value === schoolType}" @click="schoolTypeFun(item)">
                  {{ item.name }}
                </view>
              </view>
            </view>
            <!-- 地区 -->
            <view class="institution-box" v-if="areaType !== '3'">
              <view class="title">地区</view>
              <view class="main">
                <!-- 循环 -->
                <view v-for="(item,index) in areaList" :key="index"
                      :class="{active:item.code === area}" @click="areaFun(item)">
                  {{ item.name }}
                </view>
              </view>
            </view>
          </view>
          <view class='s-btn-common'>
            <uv-button type="warning" text="重置" @click="resetFun()"/>
            <uv-button type="primary" text="确认" @click="closePicker()"/>
          </view>
        </view>
      </slot>
    </uv-action-sheet>
  </view>
</template>

<script setup>
  import targetAPI from '@/api/law/target/target';
  import targetOrgAPI from '@/api/law/target/targertOrg';
  import publicAPI from '@/api/law/public/public';
  import dataScopeAPI from '@/api/law/supDataScope/supDataScope';
  import dictAPI from '@/api/dict/dict'
  import {onLoad} from '@dcloudio/uni-app';
  import {ref, reactive, getCurrentInstance, defineProps} from 'vue';
  import config from "@/common/config";
  let imgMinioPath = ref(config.IMG_MINIO_PATH);
  const {proxy} = getCurrentInstance();
  const props = defineProps({
    rowId: {
      type: String,
      default: ''
    },
    entryType: {
      type: String,
      default: ''
    },
  });

  let title = ref('');
  let loading = ref(false);
  let userInfo = ref(uni.getStorageSync('userInfo'));
  const queryForm = reactive({ // 查询条件
    name: '', // 机构名称（学校/配餐单位）
    schoolPropertiesCode: '', // 办学性质
    doSchoolTypeCode: '', // 办学类型
    countyId: '', // 地区
    params: {
      sourceIds: []
    }
  });
  // 筛选图标控制
  const iconFlag = ref(false);

  const placeholder = ref("");
  /** 数据加载 */
  onLoad(async (e) => {
    if (e.entryType === '5') {
      title.value = '选择配餐单位';
      placeholder.value = "配餐单位名称";
      await getDataScopeList('03');
      await getCaterList();
    } else {
      title.value = '选择学校';
      placeholder.value = "学校名称";
      await getDataScopeList('02');
      await getSchoolList();
      await getSchoolNatureList(); // 办学性质
      await getSchoolTypeList();// 办学类型
    }
    await getAreaList();// 地区
    await getTargetOrgList();
  });

  /** 搜索 */
  let searchFun = async () => {
    if (props.entryType === '5') {
      await getCaterList();
    } else {
      await getSchoolList();
    }
  };

  /** 清空搜索 */
  let clearFun = () => {
    searchFun();
  }

  /** 获取指标机构关联列表 */
  let selectKeys = ref([]);
  let getTargetOrgList = async () => {
    let res = await proxy.http.asyncPost(targetOrgAPI.targetOrgPage, {targetId: props.rowId},false);
    if (res.code === 0) {
      selectKeys.value = [...res.data.records.map(item => item.orgId)];
      changeCheckbox(selectKeys.value);
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 根据片区获取信息 */
  let sourceIds = ref([]);
  let getDataScopeList = async (type) => {
    let query = {
      sourceType: type,
      createOrgId: userInfo.value.user.orgId,
      dataScopeType: '2'
    }
    let res = await proxy.http.asyncPost(dataScopeAPI.dataScopeInfo, query,false);
    if (res.code === 0) {
      sourceIds.value = res.data.choose;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  }

  /** 获取配餐单位列表 */
  let getCaterList = async () => {
    queryForm.params.sourceIds = sourceIds.value;
    let res = await proxy.http.asyncPost(publicAPI.getOrgCaterNoTenantId, queryForm);
    if (res.code === 0) {
      groupList.value = res.data;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 获取学校列表 */
  let getSchoolList = async () => {
    queryForm.params.sourceIds = sourceIds.value;
    if(props.entryType == '3'){
      queryForm.schoolFlag = 1
    }
    let res = await proxy.http.asyncPost(publicAPI.getOrgSchoolNoTenantId, queryForm);
    if (res.code === 0) {
      groupList.value = res.data;
    } else {
      await uni.showToast({title: res.msg, icon: 'none'});
    }
  };

  /** 树组件 */
  const allBoxValue = ref([]); // 默认选择0
  const checkboxValue = ref([]); // 选中的数组所有的值
  const groupList = ref([]); // 选择数组
  const allCheck = ref(false);
  // 勾选
  const changeCheckbox = (e) => {
    //循环列表先都置为false （未选中状态）
    groupList.value.forEach((a) => {
      a.checked = false
      allCheck.value = false
    });
    //然后假如checkboxGroup传过来的 detail.value中有某个id则把这些元素的checked属性置为true(选中状态)
    groupList.value.forEach((a) => {
      e.forEach((b) => {
        if (a.value === b) {
          a.checked = true
        }
      })
    });
    //如果选中的checkbox的value的数组长度和后端传过来的数组长度相等则为全选状态 allCheck为true
    if (e.length >= groupList.value.length) {
      allCheck.value = true
    }
    //将选中的数组保存在某个ref中
    checkboxValue.value = e
    changeCss();
  };
  // 全选/反选
  const allChecked = () => {
    //更改选中状态
    allCheck.value = !allCheck.value
    if (allCheck.value === true) {
      groupList.value.forEach((a) => {
        a.checked = true
      })
      checkboxValue.value = groupList.value.map((item) => {
        return item.id
      })
    } else {
      groupList.value.forEach((a) => {
        a.checked = false
      })
      checkboxValue.value = []
    }
    changeCss();
  };

  let checkType = ref(0)
  const changeCss = () =>{
    if(!checkboxValue.value.length){
      checkType.value = 0//未选
    }else if(groupList.value.length == checkboxValue.value.length){
      checkType.value = 2//全选
    }else{
      checkType.value = 1//半选
    }
  }
  /** 筛选下拉组件 */
  const searchPicker = ref(); // 实例化
  let searchFlag = ref(true);
  let searchHistory = ref({
    schoolPropertiesCode: '', // 办学性质
    doSchoolTypeCode: '', // 办学类型
    countyId: '', // 地区
  });
  // 下拉-打开
  const showPicker = () => {
    searchPicker.value.open();
  };
  // 下拉-取消
  const close = () => {
    if (searchFlag.value) {
      schoolNature.value = searchHistory.value.schoolPropertiesCode;
      schoolType.value = searchHistory.value.doSchoolTypeCode;
      area.value = searchHistory.value.countyId;
      queryForm.schoolPropertiesCode = schoolNature.value;
      queryForm.doSchoolTypeCode = schoolType.value;
      queryForm.countyId = area.value;
    }
  };
  // 下拉-确认
  const closePicker = () => {
    iconFlagChange();
    searchFlag.value = true;
    searchHistory.value = {
      schoolPropertiesCode: schoolNature.value,
      doSchoolTypeCode: schoolType.value,
      countyId: area.value
    };
    queryForm.schoolPropertiesCode = schoolNature.value;
    queryForm.doSchoolTypeCode = schoolType.value;
    queryForm.countyId = area.value;
    searchPicker.value.close();
    searchFun();
  };
  // 筛选图标颜色控制
  function iconFlagChange () {
    if (props.entryType === '5'){
      if (area.value) {
        iconFlag.value = true;
      } else {
        iconFlag.value = false;
      }
    } else {
      if (area.value || schoolNature.value || schoolType.value) {
        iconFlag.value = true;
      } else {
        iconFlag.value = false;
      }
    }
  }

  // 下拉-重置
  const resetFun = () => {
    iconFlag.value = false;
    searchFlag.value = false;
    queryForm.schoolPropertiesCode = '';
    queryForm.doSchoolTypeCode = '';
    queryForm.countyId = '';
    schoolNature.value = '';
    schoolType.value = ''
    area.value = '';
    searchPicker.value.close();
    searchFun();
  }

  /** 筛选-办学性质 */
  const schoolNature = ref('');
  const schoolNatureList = ref([]);
  // 获取办学性质列表
  let getSchoolNatureList = async () => {
    let res = await proxy.http.asyncGet(dictAPI.findDataListByType('school_properties'), {},false);
    if (res.code === 0) {
      schoolNatureList.value = res.data;
    }
  };
  // 筛选选中
  const schoolNatureFun = (item) => {
    if (schoolNature.value === item.value) {
      schoolNature.value = '';
    } else {
      schoolNature.value = item.value;
    }
  };

  /** 筛选-办学类型 */
  const schoolType = ref('');
  const schoolTypeList = ref([]);
  // 获取办学类型列表
  let getSchoolTypeList = async () => {
    let res = await proxy.http.asyncGet(dictAPI.findDataListByType('do_school_type'), {},false);
    if (res.code === 0) {
      schoolTypeList.value = res.data;
    }
  };
  // 筛选选中
  const schoolTypeFun = (item) => {
    if (schoolType.value === item.value) {
      schoolType.value = ''
    } else {
      schoolType.value = item.value;
    }
  };

  /** 筛选-地区 */
  const area = ref('');
  const areaList = ref([]);
  let areaType = ref('');
  // 获取地区列表
  let getAreaList = async () => {
    let query = {};
    if (userInfo.value.user.org.county) { // 区
      areaType.value = '3';
      return;
    } else if (userInfo.value.user.org.city) { // 市
      areaType.value = '2';
      query.parentCode = userInfo.value.user.org.city;
    } else { // 省
      areaType.value = '1';
      query.parentCode = userInfo.value.user.org.province;
    }
    let res = await proxy.http.asyncPost(publicAPI.getAreaListByParentCode(query.parentCode),"",false);
    if (res.code === 0) {
      areaList.value = reactive(res.data);
    }
  };
  // 筛选选中
  const areaFun = (item) => {
    if (area.value === item.code) {
      area.value = ''
    } else {
      area.value = item.code;
    }
  };

  /** 确认提交 */
  const confirmFun = async () => {
    uni.showModal({
      title: '温馨提示',
      content: '确定添加该条数据？',
      success: async function (res) {
        if (res.confirm) {
          loading.value = false;
          let query = {
            id: props.rowId,
            entryType: props.entryType,
            orgIds: [...checkboxValue.value]
          }
          let res = await proxy.http.asyncPost(targetAPI.configTargetOrg, query);
          if (res.code === 0) {
            await uni.showToast({icon: 'success', title: '添加成功', duration: 2000});
            loading.value = true;
            setTimeout(() => {
              goBack();
            }, 1000)
          } else {
            await uni.showToast({title: res.msg, icon: 'none'});
          }
        }
      }
    })
  };

  /** 返回上一页 */
  let goBack = async () => {
    uni.$emit("refresh", {});
    await uni.navigateBack();
  };
</script>

<style scoped lang="scss">
  .cu-checked-group {
    display: flex;
    font-size: 14px;
    font-weight: normal;
    align-items: center;
    flex:1;
    .text{
      margin-left: 16rpx;
      color: #303133;
      font-size: 32rpx !important;
      line-height: 1;
    }
  }
  .cu-checkbox {
    font-family: uvicon-iconfont;
    position: relative;
    width: 18px;
    height: 18px;
    border: 2px solid #DCDFE6;
    background-color: #fff;
    box-sizing: border-box;
    border-radius: 3px;

    &.check-not-full {
      border-color: #2979ff;
      background-color: #2979ff;
      display: flex;
      align-items: center;
      justify-content: center;
      .uni-checkbox-input {
        width: 20rpx;
        height: 4rpx;
        background-color: #fff;
      }
    }
  }

</style>
